<template>
  <el-cascader
    clearable
    v-model="addressIds"
    :disabled="disabled"
    :props="areas"
    class="w-full"
    :placeholder="addressIds?addressIds.toString():'请选择区域'"
    @change="areaChange"
  />
</template>

<script>
export default {
  name: "Areas",

  // 接收 province_id、city_id、county_id
  props: {
    ids: {
      type: String,
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      //用于回显
      addressIds: '',
      selectValues: [1],
      country_id: "",
      options: [],
      areas: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          this.getArea(node, resolve);
        }
      }
    };
  },

  mounted() {
    this.addressIds = this.ids.length > 2 ? this.ids : ''
    console.log(this.ids, "省市区回显数据")
  },
  methods: {
    // 省市县三级联动
    getArea(node, resolve) {
      const {level} = node;
      if (level === 0) {
        this.$http
          .get(`/city/index`)
          .then((res) => {
            resolve(this.formatAreaData(res.data.data, level));
          });
      } else if (level === 1) {
        if (node.data) {
          this.$http
            .get(`/city/index?pid=${node.data.code}`)
            .then((res) => {
              resolve(this.formatAreaData(res.data.data, level));
            });
        }
      } else if (level === 2) {
        if (node.data) {
          this.$http.get(`/city/index?pid=${node.data.code}`).then((res) => {
            resolve(this.formatAreaData(res.data.data, level));
          });
        }

      }
    },

    // 格式化三级联动数据
    formatAreaData(data, level) {
      return data.map((item) => {
        return {
          code: item.id,
          value: item.id,
          label: item.name,
          leaf: level >= 2
        };
      });
    },

    areaChange(value) {
      this.$emit("areaChange", [...value]);
    }
  }
};
</script>
